package common.util;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5;
import com.yuntsg.ruiijn.paperana.utils.SmallTool;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class PdfUtil {

    public static List<String> pdfToTxt(String directory, String pdfName) {
        List<String> list = new ArrayList<>();
        SmallTool.printMess("directory+" + directory);
        SmallTool.printMess("pdfName+" + pdfName);
        try {
            ProcessBuilder processBuilder = new ProcessBuilder();
            processBuilder.directory(new File(directory));
            String name = pdfName.substring(0, pdfName.length() - ".pdf".length()); // 因为不同名，不好找，测试时使用这个。
            String txtFile = name + ".txt";
            if (VerifyUtil.isServer()) {
                processBuilder.command("/usr/local/bin/mutool", "convert", "-o", txtFile, pdfName);
            } else {
                processBuilder.command("D:\\mutool\\mutool", "convert", "-o", txtFile, pdfName);
            }
            processBuilder.redirectErrorStream(true);
            Process process = processBuilder.start();
            InputStream inputStream = process.getInputStream();
            String result = IoUtil.read(inputStream, Charset.forName("utf-8"));
            inputStream.close();
            String txtPath = txtFile;
            SmallTool.printMess("文件读取路径是" + txtPath);
            if (FileUtil.exist(txtPath)) {
                List<String> strings = FileUtil.readLines(txtPath, "utf-8");
                for (String string : strings) {
                    if (StringUtil.isNotNull(string)) {
                        list.add(string);
                    }
                }
                return list;
            } else {
                SmallTool.printMess("文件不存在返回null");
                return null;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    public static InputStream convertEmf(String basePath, String fileName, boolean scale) {
        String emfPath = basePath + fileName;
        String convertJpgPath = basePath + StrUtil.subBefore(fileName, ".", true) + ".jpg";
        try {
            ProcessBuilder processBuilder = new ProcessBuilder();
            processBuilder.directory(new File(basePath));

            while (true) {
                if (!FileUtil.exist(convertJpgPath)) {
                    processBuilder.command("libreoffice", "--headless", "--convert-to", "jpg", fileName);
                    processBuilder.redirectErrorStream(true);
                    Process start = processBuilder.start();
                    start.waitFor(2, TimeUnit.SECONDS);
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(start.getInputStream()));
                    String str = bufferedReader.readLine();
                    System.out.println(str);
                    if (str.contains("source file could not be loaded")) {
                        return null;
                    }
                } else {
                    if (scale) {
                        Image img = ImgUtil.scale(ImgUtil.read(convertJpgPath), 0.5f);
                        return ImgUtil.toStream(img, "jpg");
                    } else {
                        BufferedInputStream inputStream = FileUtil.getInputStream(convertJpgPath);
                        return inputStream;
                    }

                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        } finally {
            FileUtil.del(convertJpgPath);
            FileUtil.del(emfPath);
        }
    }

    public static List<ImageInfo> pdftoImages(String directory, String pdfname) {
        List<ImageInfo> imageInfos = new ArrayList<ImageInfo>();
        try {
            ProcessBuilder processBuilder = new ProcessBuilder();
            processBuilder.directory(new File(directory));
            processBuilder.command("/usr/local/bin/mutool", "extract", "-r", pdfname);
//            processBuilder.command("/mnt/ramdisk/mutool", "extract", pdfname);
            processBuilder.redirectErrorStream(true);
            Process process = processBuilder.start();
            InputStream inputStream = process.getInputStream();
            IoUtil.read(inputStream, "utf-8");
            inputStream.close();
            File[] fileList = new File(directory).listFiles();
            for (File file : fileList) {
                byte[] bytes = null;
                String n = file.getName().toLowerCase();
                if (n.endsWith(".jpeg2000") || n.endsWith(".jpg") || n.endsWith(".tiff") || n.endsWith(".bmp") || n.endsWith(".pcx") || n.endsWith(".gif") || n.endsWith(".wbmp") || n.endsWith(".png") || n.endsWith(".raw") || n.endsWith(".jpeg") || n.endsWith(".pnm") || n.endsWith(".tif") || n.endsWith(".jbig2") || n.endsWith(".jpg2")) {
                    if (n.endsWith(".jpg") || n.endsWith(".jpeg")) {
                        bytes = FileUtil.readBytes(file);
                    } else {
                        ByteArrayOutputStream bos = null;
                        try {
                            BufferedImage originalImage = ImageIO.read(file);
                            bos = new ByteArrayOutputStream();
                            ImageIO.write(ensureOpaque(originalImage), "jpg", bos);
                            bos.flush();
                            bytes = bos.toByteArray();
                        } catch (Exception e) {
                            System.out.println("bos_err_a");
                        } finally {
                            if (bos != null) {
                                try {
                                    bos.close();
                                } catch (Exception e) {
                                    System.out.println("bos_err_b");
                                }
                            }
                        }
                    }

                    if (bytes != null) {
                        ImageInfo imageInfo = new ImageInfo();
                        imageInfo.setBytes(bytes);
                        imageInfo.setMd5(new MD5().digestHex(bytes));
                        imageInfo.setName(file.getName().substring(0, file.getName().lastIndexOf(".")) + ".jpg");
                        imageInfos.add(imageInfo);
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return imageInfos;
    }


    static BufferedImage ensureOpaque(BufferedImage bi) {
        if (bi.getTransparency() == BufferedImage.OPAQUE) {
            return bi;
        }
        int w = bi.getWidth();
        int h = bi.getHeight();
        int[] pixels = new int[w * h];
        bi.getRGB(0, 0, w, h, pixels, 0, w);
        BufferedImage bi2 = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        bi2.setRGB(0, 0, w, h, pixels, 0, w);
        return bi2;
    }

    public static String getpdfurl(String pdfPath, Integer uid, Integer gid) {
        String[] prevEncryptStrArray = pdfPath.split(",");
        String newPaths = "";
        for (String str : prevEncryptStrArray) {
            String[] array = str.split("\\|");
            String fileName = "show";
            if (array.length > 3) {
                //给str赋值去掉文件名的待加密字符串
                str = str.replace("|" + array[3], "");
                fileName = array[3].replace("#_#", ".");
            }
            String encryptStrPre = uid + "|" + gid + "|" + str + "|" + System.currentTimeMillis();
            String encryptStr = XXTEASafe.encryptToBase64String(encryptStrPre, "VJpHo2naZ9");
            String suffix = ".pdf";
            if (str.contains("rar")) {
                suffix = ".rar";
            }
            String encoderFileName = URLEncoder.encode(fileName).replace("+", "%20");
            String newLink = "/attach/" + encoderFileName + "?query=" + encryptStr + "&view=true&type=" + suffix;
            newPaths = newPaths + "|" + newLink;
        }
        if (newPaths.length() > 1) {
            newPaths = newPaths.substring(1);
        }
        return newPaths;
    }
}
